package utile

import (
	"context"
	"encoding/json"
	"fmt"
	"go.etcd.io/etcd/clientv3"
	"logstash/config"
	"logstash/logger"
	"time"
)

type Etcd struct {
	client *clientv3.Client
	keys   []string
}

type Edata struct {
	Key string
	val string
}

var etcd = &Etcd{}

func NewEtcd() (*Etcd, error) {
	etcd.keys = make([]string, 0)
	if etcd.client == nil {
		conf := config.GetConfig()
		cli, err := clientv3.New(clientv3.Config{
			Endpoints:   []string{fmt.Sprintf("%s:%s", conf.Data.Etcd.Host, conf.Data.Etcd.Port)},
			DialTimeout: 5 * time.Second,
			Username:    conf.Data.Etcd.Username,
			Password:    conf.Data.Etcd.Password,
		})
		if err != nil {
			return nil, err
		}
		etcd.client = cli
	}
	return etcd, nil
}

func GetEtcd() *Etcd {
	return etcd
}

func GetEtcdClient() (*clientv3.Client, error) {
	conf := config.GetConfig()
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   []string{fmt.Sprintf("%s:%s", conf.Data.Etcd.Host, conf.Data.Etcd.Port)},
		DialTimeout: 5 * time.Second,
		Username:    conf.Data.Etcd.Username,
		Password:    conf.Data.Etcd.Password,
	})
	if err != nil {
		return nil, err
	}
	etcd.client = cli
	return cli, nil
}

func (e *Etcd) GetPrefix() string {
	conf := config.GetConfig()
	return conf.Data.Etcd.Prefix
}

func (e *Etcd) Set(key, val string) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err := e.client.Put(ctx, key, val)
	cancel()
	if err != nil {
		logger.Errorf("etcd set data failed , err: %s", err)
		fmt.Printf("etcd set data failed , err: %s", err)
		return err
	}
	e.keys = append(e.keys, key)
	return nil
}

func (e *Etcd) Get(key string) (data string, err error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	resp, err := e.client.Get(ctx, key)
	cancel()
	if err != nil {
		logger.Errorf("etcd get data failed , err: %s", err)
		fmt.Printf("etcd get data failed , err: %s", err)
		return "", err
	}

	for _, ev := range resp.Kvs {
		data = string(ev.Value)
		//fmt.Printf("%s:%s\n", ev.Key, ev.Value)
	}
	return data, nil
}

func (e *Etcd) Del(key string) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	_, err := e.client.Delete(ctx, key)
	cancel()
	if err != nil {
		logger.Errorf("etcd del data failed , err: %s", err)
		fmt.Printf("etcd set del failed , err: %s", err)
		return err
	}

	return nil
}

func (e *Etcd) Close() {
	e.client.Close()
	e.client = nil
}

func (e *Etcd) Run() {
	rch := e.client.Watch(context.Background(), "test") // <-chan WatchResponse
	for wresp := range rch {
		for _, ev := range wresp.Events {
			fmt.Printf("Type: %s Key:%s Value:%s\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
		}
	}
}

func (e *Etcd) GetConfigFromEtcdByIp() (string, error) {
	ip := GetOutboundIP()
	fmt.Printf("ip : %s \n", ip)
	key := fmt.Sprintf("/%s/%s", e.GetPrefix(), ip)
	return e.Get(key)
}

func (e *Etcd) SetConfigFromEtcd(conf config.Yml) error {
	ip := GetOutboundIP()
	key := fmt.Sprintf("/%s/%s", e.GetPrefix(), ip)
	data, _ := json.Marshal(conf)
	return e.Set(key, string(data))
}

func (e *Etcd) InitProjectConfig(confData *config.Yml) error {
	//从ETCD获取配置
	confstr, err := e.GetConfigFromEtcdByIp()
	if err != nil {
		return fmt.Errorf("Etcd获取配置失败,错误信息：%s ", err)
	}
	//当ETCD中没有获取到配置信息时，则从本地获取初始化配置信息并存储到ETCD
	if len(confstr) > 1 {
		err = json.Unmarshal([]byte(confstr), confData)
		fmt.Printf("conf form etcd: %+v \n", confData)
	} else {
		fmt.Printf("conf form yml : %+v \n", confData)
		//存储配置信息到ETCD
		err = e.SetConfigFromEtcd(*confData)
		if err != nil {
			return fmt.Errorf("Etcd保存配置失败,错误信息：%s ", err)
		}
		//再次从ETCD获取配置信息，检测该信息是否正确存储
		confstr, err = e.GetConfigFromEtcdByIp()
		if err != nil {
			return fmt.Errorf("Etcd获取配置失败,错误信息：%s ", err)
		}
		fmt.Printf("reget conf form etcd : %s \n", confstr)
	}
	return nil
}

//func (e *Etcd) Watch() {
//	ip := GetOutboundIP()
//	key := fmt.Sprintf("/%s/%s", etcd.prefix, ip)
//	// 初始化连接etcd
//	cli, err := GetEtcdClient()
//	if err != nil {
//		logger.Error("连接etcd失败:", err)
//		return
//	}
//	logger.Info("开始监控key:", key)
//
//	conf := config.GetConfig()
//
//	// Watch操作
//	for {
//		var getConfSucc = true
//		wch := cli.Watch(context.Background(), key)
//		for resp := range wch {
//			for _, ev := range resp.Events {
//				// DELETE处理
//				if ev.Type == clientv3.EventTypeDelete {
//					logger.Warnf("删除Key[%s]配置", key)
//					continue
//				}
//				// PUT处理
//				if ev.Type == clientv3.EventTypePut && string(ev.Kv.Key) == key {
//					err = json.Unmarshal(ev.Kv.Value, conf.Data)
//					if err != nil {
//						logger.Error("反序列化key[%s]失败:", err)
//						getConfSucc = false
//						continue
//					}
//				}
//				logger.Debugf("get config from etcd ,Type: %v, Key:%v, Value:%v\n", ev.Type, string(ev.Kv.Key), string(ev.Kv.Value))
//			}
//			if getConfSucc {
//				logger.Debugf("get config from etcd success, %v", conf.Data)
//				//TODO 通知文件监控
//				//_ = tailf.UpdateConfig(collectConf)
//				GetTailMgr().UpdateConfig()
//			}
//		}
//	}
//}
